package com.sbl.bajw.pc.service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sbl.bajw.common.MyBatisDao;
import com.sbl.bajw.common.web.MessageException;
import com.sbl.bajw.common.web.RequestUnit;
import com.sbl.bajw.common.web.SessionUnit;
import com.sbl.bajw.common.web.WebContext;
import com.sbl.bajw.mapper.OperationLogModelDao;
import com.sbl.bajw.mapper.TermpostDao;
import com.sbl.bajw.mapper.TodoFinishDao;
import com.sbl.bajw.pc.model.AttFileModel;
import com.sbl.bajw.pc.model.LogTModel;
import com.sbl.bajw.pc.model.OperationLogModel;
import com.sbl.bajw.pc.model.TermpostModel;
import com.sbl.bajw.pc.model.TodoFinishModel;
import com.sbl.bajw.util.FileUpload;
import com.sbl.bajw.util.JsonUtil;
import com.sbl.bajw.util.LogUtil;

@Service
public class TermpostService {

	@Resource
	private TermpostDao dao;

	@Resource
	private TodoFinishDao finishdao;
	
	@Resource
	private LogTModelService logService;
	
	@Resource
	private AttFileService attfileService;

	@Resource
	private OperationLogModelDao op_dao;
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");

	@Resource
	MyBatisDao gridDao;

	static Logger log;

	static {
		log = LogUtil.getLogger("termpost");
	}

	@Transactional(readOnly = false)
	public void create(TermpostModel model) throws MessageException {
		log.info( "开始上传,userid:" + RequestUnit.getString("user_id"));
		String userId = SessionUnit.getUserId();
		String todo_id = RequestUnit.getString("todo_id");
		if (userId == null || userId.equals("")) {
			userId = RequestUnit.getString("user_id");
		}
		checkModel(model, true);
		model.setTakedate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
		model.setPicfileids(model.getId());
		model.setUserid(userId);
		model.setFulldeptid("0-1-");

		if (todo_id != null && !todo_id.equals("")) {
			TodoFinishModel finishModel = new TodoFinishModel();
			finishModel.setTodoId(todo_id);
			finishModel.setFinishX(model.getMapx());
			finishModel.setFinishY(model.getMapy());
			finishModel.setUserId(userId);
			finishdao.insert(finishModel);
		}

		log.info(SessionUnit.getSessionId() + "属性入库成功");
		try {
			log.info(SessionUnit.getSessionId() + "文件开始上传");
			uploadFile(model);
			if(model.getQualified().equals("是")){
				if(!model.getBuildingCode().substring(0, 9).equals("440306011") || model.getBuildingCode().length() != 19) {
					model.setQualified("否");
					model.setUnqualifiedReason("2");
				}
			}else{
				if(!model.getBuildingCode().substring(0, 9).equals("440306011") || model.getBuildingCode().length() != 19) {
					model.setUnqualifiedReason("3");
				}
			}
			dao.insert(model);
		} catch (Exception e) {
			log.info(SessionUnit.getSessionId() + "文件上传异常：" + e.getMessage());
			e.printStackTrace();
			throw new MessageException("图片上传失败", "3");
		}
		
		LogTModel lt = new LogTModel();
		lt.setUserid(model.getUserid());
		if(model.getClassType() != null && !model.getClassType().equals("")){
			int i = Integer.parseInt(model.getClassType()) + 2;
			lt.setCode(i + "");
		}
		lt.setOperatingContent(sdf.format(new Date()) + "，" + model.getUserid() + "在" + model.getAddr() + "采集信息，类型为" + model.getClassType());
		log.info("==>日志"+lt.getUserid()+","+lt.getCode());
		logService.insert(lt);
		
		//出租屋采集信息入库操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(model.getUserid());
		entity.setOperationcontent("出租屋信息采集");
		entity.setOperationname("出租屋信息采集");
		entity.setActionid("1");
		op_dao.insert(entity);
		
	}

	public void update(TermpostModel model) throws MessageException {
		log.info(SessionUnit.getSessionId() + "开始上传,userid:" + RequestUnit.getString("user_id"));
		String userId = SessionUnit.getUserId();
		if (userId == null || userId.equals("")) {
			log.info(SessionUnit.getSessionId() + "没有登录");
			throw new MessageException("请登录", "4");
		}
		checkModel(model, false);
		model.setTakedate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
		model.setPicfileids(model.getId());
		model.setUserid(userId);
		model.setFulldeptid("0-1-");
		dao.update(model);
		log.info(SessionUnit.getSessionId() + "属性入库成功");
		try {
			log.info(SessionUnit.getSessionId() + "文件开始上传");
			uploadFile(model);
		} catch (Exception e) {
			log.info(SessionUnit.getSessionId() + "文件上传异常：" + e.getMessage());
			e.printStackTrace();
			throw new MessageException("图片上传失败", "3");
		}
	}

	public String uploadFile(TermpostModel model) throws Exception {
		String id = RequestUnit.getString("id");

		if (id == null || id.equals("")) {
			throw new MessageException("ID不能为空", "2");
		}

		FileItem item = RequestUnit.getFileItem("img");
		String resultPath = "";
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssS");

		if (item != null) {
			String dataStr = sf.format(Calendar.getInstance().getTime());
			String userid = RequestUnit.getString("user_id");
			AttFileModel filemodel = new AttFileModel();
			filemodel.setBusinessType("1");
			filemodel.setFileDir("termpost");
			filemodel.setFileName(dataStr + "_img_" + id);
			filemodel.setGroupid(id);
			filemodel.setItem(item);
			filemodel.setUserid(userid);
			attfileService.insert(filemodel);
			log.info(SessionUnit.getSessionId() + "图片上传成功:" + resultPath);
			model.setQualified("是");
		} else {
			log.info(SessionUnit.getSessionId() + "没有图片数据");
			model.setQualified("否");
			model.setUnqualifiedReason("1");
		}

		FileItem record = RequestUnit.getFileItem("voice");
		if (record != null) {
			String path = WebContext.getRequest().getSession().getServletContext().getInitParameter("UploadPath");
			String dataStr = sf.format(Calendar.getInstance().getTime());
			resultPath = "images/upload/" + FileUpload.saveFile(record, path + "/images/upload/", dataStr + "_record_" + id);
			log.info(SessionUnit.getSessionId() + "录音上传成功:" + resultPath);
			HashMap<String, String> parm = new HashMap<String, String>();
			parm.put("path", resultPath);
			parm.put("groupid", id);
			parm.put("filetype", "record");
			dao.insertAttfile(parm);
		} else {
			log.info(SessionUnit.getSessionId() + "没有录音数据");
		}
		return resultPath;
	}

	public String getAttfile(String picid) {
		List<HashMap<String, String>> list = dao.getAttfile(picid);
		String result = JsonUtil.ConvertArrayToJson(list);
		return result;
	}

	public String list(HashMap<String, Object> parm) {
		String str = gridDao.selectPage(TermpostDao.class, parm, "getList");
		
		//出租屋列表查询操作日志
		OperationLogModel entity = new OperationLogModel();
		if(parm.get("userId") != null){
			entity.setOperationuserid(parm.get("userId").toString());
		}else{
			entity.setOperationuserid(SessionUnit.getUserId());
		}
		entity.setOperationcontent("出租屋列表查询");
		entity.setOperationname("出租屋采集查询");
		entity.setActionid("4");
		op_dao.insert(entity);
		
		return str;
	}

	public String getTermpostListByCode(HashMap<String, Object> parm) {
		String str = gridDao.selectPage(TermpostDao.class, parm,
				"getTermpostListByCode");
		
		//根据楼栋编码查找所有数据操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(SessionUnit.getUserId());
		entity.setOperationcontent("根据楼栋编码查找所有数据");
		entity.setOperationname("根据楼栋编码查找所有数据");
		entity.setActionid("4");
		op_dao.insert(entity);
		
		return str;
	}

	public List<HashMap<String, Object>> getList(HashMap<String, String> parm) {
		List<HashMap<String, Object>> list = dao.getList(parm);
		
		//出租屋列表导出操作日志
		OperationLogModel entity = new OperationLogModel();
		if(parm.get("userId") != null){
			entity.setOperationuserid(parm.get("userId").toString());
		}else{
			entity.setOperationuserid(SessionUnit.getUserId());
		}
		entity.setOperationcontent("出租屋列表导出");
		entity.setOperationname("出租屋列表导出");
		entity.setActionid("5");
		op_dao.insert(entity);
		
		return list;
	}

	public HashMap<String, Object> getTermpostModel(String id, String userId) {
		HashMap<String, Object> model = dao.getTermpostModel(id);
		
		//APP用户出租屋详情查询操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(userId);
		entity.setOperationcontent("出租屋详情查询");
		entity.setOperationname("出租屋详情查询");
		entity.setActionid("4");
		op_dao.insert(entity);
		
		return model;
	}

	public String listPage() {
		String result = gridDao.selectPage(TermpostDao.class, null, "listPage");
		return result;
	}

	public String fuzzySearch(HashMap<String, Object> parm) {
		String model = gridDao.selectPage(TermpostDao.class, parm,
				"fuzzySearch");
		
		//出租屋列表模糊搜索操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(parm.get("userId").toString());
		entity.setOperationcontent("出租屋列表模糊搜索");
		entity.setOperationname("出租屋列表模糊搜索");
		entity.setActionid("4");
		op_dao.insert(entity);
		
		return model;
	}
	
	public String getZdryList(HashMap<String, Object> parm){
		String json = gridDao.selectPage(TermpostDao.class, parm, "getZdryList");
		return json;
	}

	public void checkModel(TermpostModel model, boolean checkExit)
			throws MessageException {
		if (model == null) {
			throw new MessageException("数据为空", "2");
		}
		if (model.getId() == null || model.getId().equals("")) {
			throw new MessageException("ID不能为空", "2");
		}

		if (checkExit) {
			int count = dao.checkExits(model.getId());
			if (count > 0) {
				throw new MessageException("重复提交", "5");
			}
		}

		if (model.getMapx() == null || model.getMapx().equals("")) {
			throw new MessageException("经度不能为空", "2");
		}
		if (model.getMapy() == null || model.getMapy().equals("")) {
			throw new MessageException("纬度不能为空", "2");
		}
		if (model.getAddr() == null || model.getAddr().equals("")) {
			throw new MessageException("地址不能为空", "2");
		}
		if (model.getBuildingCode() == null
				|| model.getBuildingCode().equals("")) {
			throw new MessageException("楼栋编码不能为空", "2");
		}
		if (model.getBuildingCode().length() != 19) {
			throw new MessageException("楼栋编码必须为19位", "2");
		}
		if (model.getBuildingType() == null
				|| model.getBuildingType().equals("")) {
			throw new MessageException("楼栋类型不能为空", "2");
		}
		if (model.getTelno() == null || model.getTelno().equals("")) {
			throw new MessageException("电话号码不能为空", "2");
		}
	}

}
